<!--
 * @Author: doing
 * @Date: 2023-08-10 10:21:19
 * @LastEditors: git config user.name && git config user.email
 * @LastEditTime: 2023-09-02 21:25:13
 * @FilePath: \background-management-system\src\pages\advert\index.vue
 * @Description: 
 * 广告管理页面
 * Copyright (c) 2023 by 1540265624@qq.com, All Rights Reserved. 
-->
<template>
    <div>
        <!-- 卡片视图区域 -->
        <el-card v-loading="isAdvertListLoading">
            <!-- 实现表单模块 -->
            <el-form ref="searchRef" :model="searchForm" class="flex">
                <el-form-item label="标题" class="mr-4" prop="title">
                    <el-input placeholder="请输入广告标题" v-model="searchForm.title"></el-input>
                </el-form-item>
                <el-form-item label="状态:" class="mr-4" prop="status">
                    <el-select v-model="searchForm.status" clearable filterable style="width: 85px">
                        <el-option v-for="item in statusOptions" :key="item.code" :label="item.name" :value="item.code">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-button type="primary" @click="findAdvert"  v-permission="['advert:search']">
                    <el-icon style="vertical-align: middle;">
                        <search />
                    </el-icon>
                    <span style="vertical-align: middle;">查询</span>
                </el-button>
                <el-button @click="resetAdvertList">
                    <el-icon style="vertical-align: middle;">
                        <RefreshLeft />
                    </el-icon>
                    <span style="vertical-align: middle;">重置</span>
                </el-button>
                <el-button type="primary" @click="handleAdd" v-permission="['advert:add']">
                    <el-icon style="vertical-align: middle;">
                        <CirclePlus />
                    </el-icon>
                    <span style="vertical-align: middle;">新增</span>
                </el-button>
            </el-form>

            <!-- 实现表格和分页 -->
                <el-table :data="advertList" border :table-layout="tableLayout" :cell-style="{ textAlign: 'center' }" :header-cell-style="{textAlign: 'center'}">
                    <el-table-column type="index" label="序号" porp="id"></el-table-column>
                    <el-table-column label="广告标题" prop="title"></el-table-column>
                    <el-table-column label="图片" prop="imageUrl" min-width="130px">
                        <template #default="{ row }">
                            <el-image style="width: 100px; height: 100px" :src="row.imageUrl" :fit="fit">
                                <template #error>
                                    <div class="image-slot">
                                        <el-icon>
                                            <PictureFilled />
                                        </el-icon>
                                    </div>
                                </template>
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column label="广告链接" prop="advertUrl">
                        <template #default="{ row }">
                            <a src="row.advertUrl" target="row.advertTarget">{{ row.advertUrl }}</a>
                        </template>
                    </el-table-column>
                    <el-table-column label="广告位置" prop="position"></el-table-column>
                    <el-table-column label="排序位置" prop="sort"></el-table-column>
                    <el-table-column label="状态" prop="status">
                        <template v-slot="scope">
                            <el-tag type="success" v-if="scope.row.status">正常</el-tag>
                            <el-tag type="warning" v-else>不正常</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="更新时间" prop="updateDate">
                        <template  #default="{ row }">
                            {{ formatTime(row.updateDate) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="auto" min-width="280px">
                        <template v-slot="scope">
                            <el-row :gutter="20" class="flex justify-center">
                                <el-button type="success" @click="handleEdit(scope.row)" class="btn"
                                v-permission="['advert:edit']"
                                >
                                    编辑
                                </el-button>
                                <el-button type="danger" @click="handleDelete(scope.row.id)" class="btn"
                                v-permission="['advert:delete']"
                                >
                                    删除
                                </el-button>
                            </el-row>
                        </template>
                    </el-table-column>
                </el-table>

            <el-pagination v-model:current-page="page.current" v-model:page-size="page.size"
                :page-sizes="[20, 50, 100]" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" class="pagination" />

        </el-card>

        <!-- 抽屉组件 -->
        <form-drawer ref="formDrawerRef" :title="drawerTitile" :destroyOnClose="true" @submit="drawerSubmit"
            @clean="cleanForm">
            <el-form :rules="rules" ref="formRef" :model="formDrawerData" label-width="100px" label-position="right"
                style="width: 400px">
                <el-form-item label="广告图片：" prop="imageUrl">
                    <!-- 上传图片 -->
                    <el-upload class="avatar-uploader" action="" accept="image/*" :show-file-list="false"
                        :http-request="uploadMainImg">
                        <img v-if="formDrawerData.imageUrl" :src="formDrawerData.imageUrl" class="avatar">
                        <i v-else class="avatar-uploader-icon">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="广告标题：" prop="title">
                    <el-input v-model="formDrawerData.title" />
                </el-form-item>

                <el-form-item label="广告链接：" prop="advertUrl">
                    <el-input v-model="formDrawerData.advertUrl" />
                </el-form-item>

                <el-form-item label="跳转方式：" prop="advertTarget">
                    <!-- "_blank", "_self" -->
                    <el-select v-model="formDrawerData.advertTarget" clearable style="width:185px">
                        <el-option label="新窗口打开" value="_blank"></el-option>
                        <el-option label="当前窗口打开" value="_self"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="状态：" prop="status">
                    <el-radio-group v-model="formDrawerData.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="广告位置：" prop="position">
                    <el-input-number v-model="formDrawerData.position" :min="1" :max="10000" style="width: 300px">
                    </el-input-number>
                </el-form-item>

                <el-form-item label="排序：" prop="sort">
                    <el-input-number v-model="formDrawerData.sort" :min="1" :max="10000" style="width: 300px">
                    </el-input-number>
                </el-form-item>
            </el-form>
        </form-drawer>
    </div>
</template>
<script setup>
import { computed, ref, reactive, onMounted, nextTick  } from 'vue'
import FormDrawer from '~/components/FormDrawer.vue'
import {
    showModal,
    toast,
    formatTime
} from '~/composables/util.js'
import {
    deleteUser,
} from '~/api/user.js'
import {
    getAdvertList,
    addAdvert,
    deleteAdvert,
    updataAdvert,
    uploadPic,
    deletePic
} from '~/api/advert.js'
//初始化数据开始
const fit = ref('contain')
const tableLayout = ref('fixed')
const isAddOrEdit = ref(true)
const isAdvertListLoading = ref(false)
const drawerTitile = computed(() => isAddOrEdit.value ? '新增' : '修改')
const advertList = ref([])
const page = reactive({
    current: 1,
    size: 20,
    total: 0
})
const Init = async function () {
    isAdvertListLoading.value = true
    const body = {...page,...searchForm}
    console.log('传递参数为')
    console.log(body)
    await getAdvertList(body).then(res => {
        advertList.value = res.data.data.records
        page.total = res.data.data.total
    })
    isAdvertListLoading.value = false
}

onMounted(() => {
    Init()
})

//初始化数据结束

//分页内容开始(待开发)
const disabled = ref(false)
const background = ref(true)

const handleSizeChange = async function () {
    Init()
}
const handleCurrentChange = async function () {
    Init()
}
//分页内容结束

//操作栏开始
//删除操作
const handleDelete = function (id) {
    showModal('是否要删除该数据?').then(async () => {
        toast('正在删除中...', 'info', false, 3000)
        await deleteAdvert(id).then(res => {
            toast('删除成功')
            //将页面引导到第一页
            resetAdvertList()
        }).finally(() => {
        })
    }).catch(() => {

    })
}
//删除结束


//编辑开始
const formDrawerRef = ref(null)
const formRef = ref(null)
const formDrawerData = reactive({})
const oldImageUrl = ref('')  //编辑时候查询出来的那张照片
const isSubmit = ref(false)


//表单验证规则
const rules = {
    imageUrl: [
        { required: true, message: '请上传广告图片', trigger: 'blur' }
    ],
    title: [
        { required: true, message: '请输入广告标题', trigger: 'blur' }
    ],
    advertUrl: [
        { required: true, message: '请输入广告链接', trigger: 'blur' }
    ],
    advertTarget: [
        { required: true, message: '请选择打开方式', trigger: 'change' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ],
    position: [
        { required: true, message: '请输入广告位置', trigger: 'blur' }
    ],
    sort: [
        { required: true, message: '请输入排序号', trigger: 'blur' }
    ],
}
//打开抽屉
const handleEdit = async function (item) {
    console.log(item)
    formDrawerRef.value.open()
    await nextTick(()=>{
        isAddOrEdit.value = false
        formDrawerData.id = item.id
        formDrawerData.imageUrl = item.imageUrl
        formDrawerData.title = item.title
        formDrawerData.advertUrl = item.advertUrl
        formDrawerData.advertTarget = item.advertTarget
        formDrawerData.status = item.status
        formDrawerData.position = item.position
        formDrawerData.sort = item.sort
        //记录一下旧照片的地址
        oldImageUrl.value = item.imageUrl
    })
}

//新增操作
const handleAdd = async function () {
    console.log(formDrawerData)

    formDrawerRef.value.open()
    formDrawerRef.value.hideLoading()
    
    await nextTick(()=>{
        isAddOrEdit.value = true
        //删除掉id
        delete formDrawerData.id
    })
}

// 删除图片
const deleteImg = function (imageUrl) {
    // 进行编辑的操作
        // 发送请求删除数据库中的原本图片链接
        deletePic(imageUrl).then(res => {
            toast('删除图片成功')
        }).catch(err=>{
            console.log(err)
        })
}

// 上传图片, file 上传的图片对象
const uploadMainImg = function (file) {
    //创建表单结构
    console.log(file)
    const data = new FormData()
    data.append('file', file.file)

    uploadPic(data).then(res => {
        // 回显图片
        formDrawerData.imageUrl = res.data.data
        // 将之前的图片删除，
        if(oldImageUrl.value !== ''){
            deleteImg(oldImageUrl.value)
        }
        //很重要
        oldImageUrl.value = res.data.data
        
    }).catch(error => {
        console.log(error)
        toast('上传失败', "error")
    })
}


//提交表单
const drawerSubmit = async () => {

    const data = {...formDrawerData}
    console.log('提交的数据为:')
    console.log(data)

    formRef.value.validate(async (valid) => {
        formDrawerRef.value.showLoading()
        if (!valid) {
            formDrawerRef.value.hideLoading()
            return false
        } else {
            formDrawerRef.value.showLoading()
            const fn = isAddOrEdit.value ? addAdvert(data) : updataAdvert(data)
            await fn
                .then(res => {
                    //后续可以加判断操作
                    console.log(res)  //进一步删除原本图片
                    isSubmit.value = true
                    formDrawerRef.value.close()
                    toast(drawerTitile.value + '成功')
                    //分页至于第一页
                    resetAdvertList()
                })
                .finally(() => {
                    isSubmit.value = false
                    formDrawerRef.value.hideLoading()
                })
        }
    })
}

//销毁该组件
const cleanForm = function () {
    if(formDrawerData.imageUrl && !isSubmit.value && isAddOrEdit.value){
        deleteImg(formDrawerData.imageUrl)
    }
    //在这里置空  这里主要针对第一次打开抽屉的赋值后的状态,清空表单
    formRef.value.resetFields()
}

//编辑结束

//操作栏结束


//查找按钮 重置按钮 新增按钮数据开始
const searchRef = ref(null)
const searchForm = reactive({})
const statusOptions = [
    { code: 0, name: '禁用' },
    { code: 1, name: '正常' }
]
//查找操作
const findAdvert = async function () {
    page.current = 1
    Init()
}
//重置操作
const resetAdvertList = function(){
    searchRef.value.resetFields()
    page.current = 1
    Init()
}

//查找按钮 重置按钮 新增按钮数据结束



//使用watch进行监听事件开始(开发进行检测作用)
// watch(form, (newVal, oldVal) => {
//     console.log(newVal)
// }, { immediate: true });
//使用watch进行监听事件结束
</script>
<style scoped>
.form {
    @apply flex justify-start items-center
}

.btn{
    margin: 0 10px;
}

.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}


.roleList-scrollbar {
    max-width: 600px;
    max-height: 160px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>